package com.example.shirodemo.service.impl;

import com.example.shirodemo.constant.HttpCode;
import com.example.shirodemo.constant.StatusCode;
import com.example.shirodemo.constant.ValuesCode;
import com.example.shirodemo.dto.ResponseResult;
import com.example.shirodemo.entity.SMenu;
import com.example.shirodemo.entity.SRole;
import com.example.shirodemo.entity.SUser;
import com.example.shirodemo.entity.SUserRole;
import com.example.shirodemo.mapper.SMenuMapper;
import com.example.shirodemo.mapper.SRoleMapper;
import com.example.shirodemo.mapper.SUserMapper;
import com.example.shirodemo.mapper.SUserRoleMapper;
import com.example.shirodemo.service.UserService;
import com.example.shirodemo.utils.CommonUtils;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 绫小路
 * @date 2021/1/10 17:45
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private SUserMapper sUserMapper;
  @Autowired
  private SRoleMapper sRoleMapper;
  @Autowired
  private SMenuMapper sMenuMapper;
  @Autowired
  private SUserRoleMapper sUserRoleMapper;

  @Override
  public SUser getUserByUsername(String username) {
    return sUserMapper.get(username);
  }

  @Override
  public SUser getUserById(Integer id) {
    return sUserMapper.selectByPrimaryKey(id);
  }

  @Override
  public Set<String> getRolesByUsername(String username) {
    return sRoleMapper.getRoles(username);
  }

  @Override
  public List<SMenu> getMenuList(Integer userId) {
    return sMenuMapper.get(userId);
  }

  @Override
  public ResponseResult updatePassword(Integer userId, String password) {
    SUser user = new SUser();
    user.setId(userId);
    user.setSalt(CommonUtils.getSalt(4));
    user.setPassword(CommonUtils.passwordToMD5(password, user.getSalt()));
    sUserMapper.updateByPrimaryKeySelective(user);
    return new ResponseResult(HttpCode.OK, "更新成功！");
  }

  @Transactional
  @Override
  public ResponseResult register(String username, String password, String nickname) {
    if (sUserMapper.get(username) != null) {
      return new ResponseResult(HttpCode.FAIL, "账号已经存在！");
    }
    SUser user = new SUser();
    user.setUsername(username);
    user.setUsername(username);
    user.setSalt(CommonUtils.getSalt(4));
    user.setPassword(CommonUtils.passwordToMD5(password, user.getSalt()));
    user.setStatus(StatusCode.VALID);
    user.setNickname(nickname);
    user.setCreateTime(new Date());
    sUserMapper.insertSelective(user);
    //初始化角色
    SRole role = sRoleMapper.get(ValuesCode.INIT_ROLE, 1);
    SUserRole userRole = new SUserRole();
    userRole.setUserId(user.getId());
    userRole.setRoleId(role.getId());
    sUserRoleMapper.insertSelective(userRole);
    return new ResponseResult(HttpCode.OK, "注册成功！");
  }
}
